<?php
namespace App\Http\Resources\Team;
use App\Http\Resources\Base\BaseResource;
use App\Services\Oss\OssService;
use Illuminate\Support\Arr;

class TeamInfoResource extends BaseResource
{
    /**
     * Transform the resource into an array.
     *
     * @param $request
     */
    public function toArray($request): array
    {
        return [
            'id' => $this['id'],
            'client_user_id' => $this['client_user_id'],
            'users' => $this->handleUsers($this->users->toArray()),
            'owner' => $this->handleOwner($this->owner),
            'name' => $this->name,
            'desc' => $this->desc,
            'can_edit' => (bool)$this->pivot->can_edit,//团队编辑权限
            'created_at' => $this->parseDateTime($this['created_at']),
        ];
    }

    private function handleUsers(array $users): array
    {
        return collect($users)->map(function ($user){
            $user['mark'] = Arr::get($user,'pivot.mark','');
            $user['can_edit'] = Arr::get($user,'pivot.can_edit',0);
            unset($user['pivot']);
            return $user;
        })->toArray();
    }

    private function handleOwner($owner){
        $owner->avatar = OssService::publishUrl($owner->avatar);
        return $owner;
    }
}
